﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Generic;

namespace TripLOA.GUI.secure
{
    public partial class tripDetail : TripLOA.GUI.internationalization.LOABasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            map_1.GoogleApiKey = System.Configuration.ConfigurationManager.AppSettings["googlekey"];
            if (!IsPostBack)
            {

                map_1.SetHelp((String)HttpContext.GetGlobalResourceObject("TripLoaResource", "HelpEdit"));
                
                // set internazionalization string for map control
                map_1.InvokeJSCommand("mapStrings['passengers_in']='" + this.GetGlobalResourceObject("TripLoaResource","GeoPassIn") + "';");
                map_1.InvokeJSCommand("mapStrings['passengers_off']='" + this.GetGlobalResourceObject("TripLoaResource", "GeoPassOff") + "';");
                map_1.InvokeJSCommand("mapStrings['language_istructions']='" + this.GetGlobalResourceObject("TripLoaResource", "GeoDrivIstr") + "';");

                Security.TripLoaUser us = Security.TripLoaUserManager.Instance.getUser(User.Identity.Name);
                int id = 0;
                String stringTripID = Request.QueryString["id"];
                if (stringTripID == null) Response.Redirect("home.aspx");
                try
                {
                    id = int.Parse(stringTripID);
                }
                catch (FormatException)
                {
                    Response.Redirect("home.aspx");
                }
                detailMultiView.ActiveViewIndex = 0;
                Groupware.Trip trip = Groupware.TripManager.GetTripById(id);
                map_1.DrawTrip(trip.GetGeoTrip());
                if (trip.UserId != us.UserID)
                    Response.Redirect("home.aspx");
                Session["tripDetail_TripGW"] = trip;
                Session["tripDetail_listVehicles"] = null;
                loadLabel(trip);

                if ((trip.ReservationExpirationDate != null && trip.ReservationExpirationDate < DateTime.Now) || (trip.ReservationExpirationDate == null && trip.DepartureDate < DateTime.Now))
                {
                    rowBtnEdit.Visible = false;
                    Expiration_trip.Visible = true;
                    //Disable accept and refuse passenger
                    removeLinksManagePassenger();
                }
                

                List<Groupware.Reservation> resList = trip.GetReservations(us);
                GridViewAcceptRequests.DataSource = resList;
                GridViewAcceptRequests.DataBind();
                bool resListVisible = true;
                bool resReqListVisible = true;
                if (resList.Count <= 0)
                {
                    lblAcceptRequests.Visible = false;
                    resListVisible = false;
                }
                List<Groupware.ReservationRequest> resReqList = trip.GetPendingReservationRequests(us);
                GridViewPendingRequests.DataSource = resReqList;
                GridViewPendingRequests.DataBind();

                if (resReqList.Count <= 0)
                {
                    lblPendingRequest.Visible = false;
                    resReqListVisible = false;
                }
                panel_request.Visible = (resListVisible || resReqListVisible);
            }
            else
            {
               
                if (Session["tripDetail_Save"] == null || ((bool)Session["tripDetail_Save"]) != false)
                    return;
                Security.TripLoaUser us = Security.TripLoaUserManager.Instance.getUser(User.Identity.Name);
                int id = 0;
                String stringTripID = Request.QueryString["id"];
                if (stringTripID == null) Response.Redirect("home.aspx");
                try
                {
                    id = int.Parse(stringTripID);
                }
                catch (FormatException)
                {
                    Response.Redirect("home.aspx");
                }
                Groupware.Trip trip = (Groupware.Trip)Session["tripDetail_TripGW"];
                
            }
           

        }
        /// <summary>
        /// Remove links: "accept passenger" and "refuse passenger";
        /// it's used when the trip is expired.
        /// </summary>
        protected void removeLinksManagePassenger()
        {
                GridViewPendingRequests.Columns.RemoveAt(GridViewPendingRequests.Columns.Count-1);
                GridViewPendingRequests.Columns.RemoveAt(GridViewPendingRequests.Columns.Count - 1);
        }

        protected void GridViewPendingRequests_OnSelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
        {
            DataKey userSelected = GridViewPendingRequests.DataKeys[e.NewSelectedIndex];
            Security.TripLoaUser us = Security.TripLoaUserManager.Instance.getUser(User.Identity.Name);
            int passID = (int)userSelected[0];

            Groupware.Trip trip = (Groupware.Trip)Session["tripDetail_TripGW"];
            List<Groupware.ReservationRequest> resReqList = trip.GetPendingReservationRequests(us);
            Groupware.ReservationRequest selected = resReqList[e.NewSelectedIndex];

            //TODO: da moficare
            Session["reservation"] = selected;
            Response.Redirect("acceptPassenger.aspx?trip=" + trip.Id + "&pass=" + passID);
        }

        protected void GridViewPendingRequests_OnRowDeleting(Object sender, GridViewDeleteEventArgs e)
        {
            Security.TripLoaUser us = Security.TripLoaUserManager.Instance.getUser(User.Identity.Name);
            int idPass = (int)GridViewPendingRequests.DataKeys[e.RowIndex].Value;
            int tripID = int.Parse(Request.QueryString["id"]);
            Groupware.Trip trip = (Groupware.Trip)Session["tripDetail_TripGW"];
            List<Groupware.ReservationRequest> resReqList = trip.GetPendingReservationRequests(us);
            Groupware.ReservationRequest selected = resReqList[e.RowIndex];
            if (selected.Refuse(us, ""))
            {
                // deletes the notification for this reservation using UserId
                Groupware.Notification n = trip.GetReservationRequestNotification(selected.UserId);
                if(n != null) n.Delete();
                Response.Redirect(HttpContext.Current.Request.Url.PathAndQuery);
            }
        }

        private void loadLabel(Groupware.Trip trip)
        {
            Storage.EntityModels.VehicleTypes vehicle = trip.GetVehicles()[0].VehicleClass;
            if (trip.GetVehicles() != null)
                VehicleContent.Text = trip.GetVehicles()[0].Model;
            /*
                Car,
                Motorcycle,
                Bike,
                Train,
                Ship,
                Airplane
             */

            //If trip is draf then the user can edit your vehicle
            if (trip.Draft)
            {
                TableRowVehicles.Visible = true;
                TableRowVehiclesControl.Visible = true;
                if (Session["tripDetail_listVehicles"] == null || ((List<Storage.EntityModels.Users_VehicleDetails>)Session["tripDetail_listVehicles"]).Count <= 0)
                {
                    Security.TripLoaUser us = Security.TripLoaUserManager.Instance.getUser(User.Identity.Name);
                    List<Storage.EntityModels.Users_VehicleDetails> vehicles = us.GetProfile().UsersVehiclesDetails;
                    Session["tripDetail_listVehicles"] = vehicles;
                    int index = 0;
                    for (int i = 0; i < vehicles.Count; i++)
                    {
                        if (trip.GetVehicles()[0].Model.Equals(vehicles[i].VehicleDetails.Model))
                        {
                            index = i;
                        }
                        ddlVehicle.Items.Add(new ListItem(vehicles[i].VehicleDetails.Model, vehicles[i].Id.ToString()));
                    }
                    ddlVehicle.SelectedIndex = index;
                    map_1.Vehicles = vehicles;
                }
                VehiclesControl.getTxtComment().Text = trip.Notes;
                //Set vehicle control values 
                setTripValuesControl(trip);
            }
            else  //This is not draft and it's not possible edit vehicles
            {
                TableRowVehicles.Visible = false;
                TableRowVehiclesControl.Visible = false;

                switch (vehicle)
                {
                    case Storage.EntityModels.VehicleTypes.Airplane:
                    case Storage.EntityModels.VehicleTypes.Ship:
                    case Storage.EntityModels.VehicleTypes.Train:
                    case Storage.EntityModels.VehicleTypes.Bike:
                        rowDevRad.Visible = false;
                        rowSmoker.Visible = false;
                        rowReqLic.Visible = false;
                        rowFreeSeat.Visible = false;
                        rowEstBudget.Visible = false;
                        
                        rowSmokerEdit.Visible = false;
                        rowRequiredLicenseDriverEdit.Visible = false;
                        rowDeviationEdit.Visible = false;
                        rowFreeSeatsEdit.Visible = false;
                        rowEstimatedBudgetEdit.Visible = false;
                        break;
                    case Storage.EntityModels.VehicleTypes.Motorcycle:
                    case Storage.EntityModels.VehicleTypes.Car:
                        DevRadContent.Text = trip.DeviationRadius.ToString();
                        devRadTBox.Text = trip.DeviationRadius.ToString();
                        ReqLicCheckBoxContent.Checked = trip.RequireLicenced != null ? (bool)trip.RequireLicenced : false;
                        //ReqLicContent.Text = trip.RequireLicenced.ToString();
                        reqLicCbox.Checked = trip.RequireLicenced != null ? (bool)trip.RequireLicenced : false ;
                        FreeSeatContent.Text = trip.FreeSeats.ToString();
                        freeSeatTbox.Text = trip.FreeSeats.ToString();
                        estBudgetContent.Text = trip.EstimatedBudget.HasValue ? trip.EstimatedBudget.Value.ToString("F2") : "0";
                        esBudgetTBox.Text = trip.EstimatedBudget != null ? trip.EstimatedBudget.Value.ToString("F2") : "0";

                        rowDevRad.Visible = true;
                        rowReqLic.Visible = true;
                        rowEstBudget.Visible = true;
                        rowFreeSeat.Visible = true;

                        rowDeviationEdit.Visible = true;
                        rowRequiredLicenseDriverEdit.Visible = true;
                        rowEstimatedBudgetEdit.Visible = true;
                        rowFreeSeatsEdit.Visible = true;

                        if (vehicle == Storage.EntityModels.VehicleTypes.Car)
                        {
                            AccSmokerCheckBoxContent.Checked = trip.AcceptSmoker != null ? (bool)trip.AcceptSmoker : false;
                            //AccSmokeContent.Text = trip.AcceptSmoker.ToString();
                            accSmokeCBox.Checked = trip.AcceptSmoker != null ? (bool)trip.AcceptSmoker : false;

                            rowSmoker.Visible = true;

                            rowSmokerEdit.Visible = true;
                        }
                        else
                        {
                            rowSmoker.Visible = false;

                            rowSmokerEdit.Visible = false;
                        }
                        break;
                }
                noteTBox.Text = trip.Notes;
                noteContent.Text = trip.Notes;
            }
            bool frequent = trip.IsFrequent != null ? (bool)trip.IsFrequent : false;
            setLabelFrequent(frequent);

            CheckBoxFrequentContent.Checked = frequent;

            if (frequent)
            {
                btnShowFrequencyDetails.Visible = true;

                txtFromDayFrequencyEdit.Text = trip.FrequencyDetails.From.ToString("d");
                lblFromFrequentContent.Text = trip.FrequencyDetails.From.ToString("d");

                txtToDayFrequencyEdit.Text = trip.FrequencyDetails.To.Date.ToString("d");
                lblToFrequentContent.Text = trip.FrequencyDetails.To.Date.ToString("d");

                ptc.DeparturesTime = trip.GetFrequencyDetails();
                //int hour = trip.EstimatedTime != null ?  ((int)trip.EstimatedTime / 60) : 0;
                //int min = trip.EstimatedTime != null ?  ((int)trip.EstimatedTime % 60) : 0;
                int estimated = trip.EstimatedTime != null ? (int)trip.EstimatedTime : 0;
                ptc.TripDuration = new TimeSpan(0, estimated, 0); 

                //read-only mode
                if (detailMultiView.ActiveViewIndex == 0)
                {
                    ptc.Editable = false;
                }
                else //edit mode
                {
                    ptc.Editable = true;
                }
                
            }
            else
            {
                btnShowFrequencyDetails.Visible = false;

                DateTime departureDate;
                if (trip.DepartureDate != null) //please do not change this! I've fixed this line two times, start your brain before your hands!
                {
                    departureDate = trip.DepartureDate.Value;
                    dateTbox.Text = departureDate.ToString("d");
                    txtStartTimeEdit.Text = departureDate.ToString("HH:mm");
                    DateTime arrivalDate = trip.DepartureDate.Value.AddMinutes((double)trip.EstimatedTime);
                    txtArrivalDate.Text = arrivalDate.Date.ToString("d");
                    txtEndTimeEdit.Text = arrivalDate.ToString("HH:mm");
                }
            }
            
            
            if (trip.ReservationExpirationDate != null)
            {
                DateTime expirationDate = trip.ReservationExpirationDate.Value;
                resExpDateTBox.Text = expirationDate.ToString("d");
                txtHourExpEdit.Text = expirationDate.ToString("HH:mm");
            }
            
            esTimeTBox.Text = trip.EstimatedTime.ToString();
            //Assign Departure and Arrival in the texbox for edit
            txtDepartureEdit.Text = trip.Departure;
            txtArrivalEdit.Text = trip.Arrival;

            DepartureContent.Text = trip.Departure;
            ArrivalContent.Text = trip.Arrival;
            DateContent.Text = trip.DepartureDate.ToString();
            ResExpContent.Text = trip.ReservationExpirationDate.ToString();
            estTimeContent.Text = trip.EstimatedTime.ToString();
            DraftCheckBoxContent.Checked = trip.Draft;
            draftCbox.Checked = trip.Draft;
            if (!trip.Draft)
                draftCbox.Enabled = false;

            UpdatePanelPeriodicTrip.Update();
        }

        private void saveTrip()
        {
            int id = int.Parse(Request.QueryString[0]);
            Groupware.Trip trip = Groupware.TripManager.GetTripById(id);
            GeoRef.GeoTrip gt = map_1.EditableTrip;
            map_1.ClearMap();
            map_1.Editable = false;
            map_1.DrawTrip(gt);
            UpdatePanelMap.Update();
            //todo by Anto: và in qualche modo salvato anche il georef.trip


            //Remember: Al va no recuperando l'oggetto dalla sessione!!!!!!!!!!
            //Groupware.Trip trip = (Groupware.Trip)Session["tripDetail_TripGW"];
            
            if (trip.Draft)
            {
                VehiclesControl.save(trip, true);   
            }
            else
            {
                trip.Notes = noteTBox.Text;
                //If vehicle is Car or Motorcycle
                if (trip.GetVehicles()[0].VehicleClass.Equals(Storage.EntityModels.VehicleTypes.Car) || trip.GetVehicles()[0].VehicleClass.Equals(Storage.EntityModels.VehicleTypes.Motorcycle))
                {
                    trip.FreeSeats = byte.Parse(freeSeatTbox.Text);
                    trip.RequireLicenced = reqLicCbox.Checked;
                    trip.DeviationRadius = float.Parse(devRadTBox.Text);
                    if (esBudgetTBox.Text == "")
                        trip.EstimatedBudget = null;
                    else
                        trip.EstimatedBudget = decimal.Parse(esBudgetTBox.Text);

                    if (trip.GetVehicles()[0].VehicleClass.Equals(Storage.EntityModels.VehicleTypes.Car))
                        trip.AcceptSmoker = accSmokeCBox.Checked;
                }
            }

            string errorControlFrequency = "";
            //Se il viaggio è frequente
            if (CheckBoxFrequent.Checked)
            {
                if (!ptc.IsValid)
                {
                    //TODO: visualizzare messaggio errore
                    errorControlFrequency = ptc.ErrorMessage;
                    return;
                }
                if (ptc.ScheduledDaysNumber <= 0)
                {
                    //TODO: visualizzare messaggio errore
                    errorControlFrequency = "Non è stato selezionato alcun giorno";
                    return;
                }
                trip.IsFrequent = true;
                DateTime firstdeparture = getHourFromFrequencyControl(DateTime.Parse(txtFromDayFrequencyEdit.Text));
                trip.DepartureDate = firstdeparture;
                trip.ReservationExpirationDate = firstdeparture.Subtract(new TimeSpan(1, 0, 0));
                trip.SetFrequencyDetails(DateTime.Parse(txtFromDayFrequencyEdit.Text), DateTime.Parse(txtToDayFrequencyEdit.Text), ptc.DeparturesTime);
                trip.EstimatedTime = (short)ptc.TripDuration.TotalMinutes;
                
            }
            else
            {
                //frequencytrip.Visible = false;

                DateTime departureDate = DateTime.Parse(dateTbox.Text + " " + txtStartTimeEdit.Text);
                trip.DepartureDate = departureDate;
                DateTime arrivalDate = DateTime.Parse(txtArrivalDate.Text + " " + txtEndTimeEdit.Text);
                trip.EstimatedTime = (short)(arrivalDate.Subtract(departureDate).TotalMinutes);
                trip.ReservationExpirationDate = DateTime.Parse(resExpDateTBox.Text);
            }
            trip.Draft = draftCbox.Checked;

            trip.UpdateTrip(gt);
            Session["tripDetail_TripGW"] = trip;
            //Switch in read only mode
            detailMultiView.ActiveViewIndex = 0;
            loadLabel(trip);

        }

        protected DateTime getHourFromFrequencyControl(DateTime dt)
        {
            DayOfWeek current = dt.DayOfWeek;
            DateTime currentdate = dt;


            String[] getsethour = ptc.DeparturesTime;
            for (int i = 0; i < 7; i++)
            {
                current = dt.DayOfWeek;
                switch (current)
                {
                    case DayOfWeek.Sunday:
                        {

                            if (!getsethour[0].Equals("DayNotScheduled"))
                            {
                                DateTime found = DateTime.Parse(dt.Day + " " + dt.Month + " " + dt.Year + " " + getsethour[0]);
                                return found;
                            }
                            break;
                        }
                    case DayOfWeek.Monday:
                        {
                            if (!getsethour[1].Equals("DayNotScheduled"))
                            {
                                DateTime found = DateTime.Parse(dt.Day + " " + dt.Month + " " + dt.Year + " " + getsethour[1]);
                                return found;
                            }
                            break;
                        }
                    case DayOfWeek.Thursday:
                        {
                            if (!getsethour[2].Equals("DayNotScheduled"))
                            {
                                DateTime found = DateTime.Parse(dt.Day + " " + dt.Month + " " + dt.Year + " " + getsethour[2]);
                                return found;
                            }
                            break;
                        }
                    case DayOfWeek.Wednesday:
                        {
                            if (!getsethour[3].Equals("DayNotScheduled"))
                            {
                                DateTime found = DateTime.Parse(dt.Day + " " + dt.Month + " " + dt.Year + " " + getsethour[3]);
                                return found;
                            }
                            break;
                        }
                    case DayOfWeek.Tuesday:
                        {
                            if (!getsethour[4].Equals("DayNotScheduled"))
                            {
                                DateTime found = DateTime.Parse(dt.Day + " " + dt.Month + " " + dt.Year + " " + getsethour[4]);
                                return found;
                            }
                            break;
                        }
                    case DayOfWeek.Friday:
                        {
                            if (!getsethour[5].Equals("DayNotScheduled"))
                            {
                                DateTime found = DateTime.Parse(dt.Day + " " + dt.Month + " " + dt.Year + " " + getsethour[5]);
                                return found;
                            }
                            break;
                        }
                    case DayOfWeek.Saturday:
                        {
                            if (!getsethour[6].Equals("DayNotScheduled"))
                            {
                                DateTime found = DateTime.Parse(dt.Day + " " + dt.Month + " " + dt.Year + " " + getsethour[6]);
                                return found;
                            }
                            break;
                        }
                }
                dt = dt.AddDays(1);



            }
            return currentdate;
        }

        private void abortMod()
        {
            detailMultiView.ActiveViewIndex = 0;
            dateTbox.Text = DateContent.Text;
            freeSeatTbox.Text = FreeSeatContent.Text;
            accSmokeCBox.Checked = AccSmokerCheckBoxContent.Checked;
            reqLicCbox.Checked = ReqLicCheckBoxContent.Checked;
            resExpDateTBox.Text = ResExpContent.Text;
            devRadTBox.Text = DevRadContent.Text;
            estBudgetContent.Text = estBudgetContent.Text;
            esTimeTBox.Text = estTimeContent.Text;
            noteTBox.Text = noteContent.Text;
            draftCbox.Checked = DraftCheckBoxContent.Checked;
            
        }

        protected void startModButton_Click(object sender, EventArgs e)
        {
            detailMultiView.ActiveViewIndex = 1;
            Groupware.Trip trip = (Groupware.Trip)Session["tripDetail_TripGW"];

            //If isn't Draft, vehicles control isn't visible
            if (!trip.Draft)
            {
                TableRowVehicles.Visible = false;
                TableRowVehiclesControl.Visible = false;
            }
        }

        protected void acceptModButton_Click(object sender, EventArgs e)
        {
            saveTrip();
        }

        protected void cancelModButton_Click(object sender, EventArgs e)
        {
            map_1.ClearMap();
            map_1.Editable = false;
            Groupware.Trip grtrip = (Groupware.Trip)Session["tripDetail_TripGW"];
            map_1.DrawTrip(grtrip.GetGeoTrip());
            UpdatePanelMap.Update();
            abortMod();
        }

        protected void buttonDelete_Click(object sender, EventArgs e)
        { 
            Security.TripLoaUser us = Security.TripLoaUserManager.Instance.getUser(User.Identity.Name);
            Groupware.Trip grtrip = (Groupware.Trip)Session["tripDetail_TripGW"];
            Groupware.TripManager.deleteTrip(grtrip.Id, us.UserID);
            Response.Redirect("~/secure/CreatedTrips.aspx");
        }

        private void setTripValuesControl(Groupware.Trip trip)
        {
            
            switch (trip.GetVehicles()[0].VehicleClass)
            {
                case Storage.EntityModels.VehicleTypes.Car:
                case Storage.EntityModels.VehicleTypes.Motorcycle:
                    VehiclesControl.getTxtBudget().Text = trip.EstimatedBudget != null ? trip.EstimatedBudget.Value.ToString("F2") : String.Empty;
                    VehiclesControl.getTxtDeviation().Text = trip.DeviationRadius != null ? trip.DeviationRadius.ToString() : String.Empty;
                    VehiclesControl.getCheckBoxDriverLicense().Checked = trip.RequireLicenced != null ? (bool)trip.RequireLicenced : false;
                    VehiclesControl.getTxtSeats().Text = (trip.FreeSeats != null) ? trip.FreeSeats.ToString() : String.Empty;
                    if (trip.GetVehicles()[0].VehicleClass.Equals(Storage.EntityModels.VehicleTypes.Car))
                        VehiclesControl.getCheckBoxSmoker().Checked = trip.AcceptSmoker != null ? (bool)trip.AcceptSmoker : false;
                    break;
            }
             
            rowSmokerEdit.Visible = false;
            rowDeviationEdit.Visible = false;
            rowRequiredLicenseDriverEdit.Visible = false;
            rowFreeSeatsEdit.Visible = false;
            rowEstimatedBudgetEdit.Visible = false;
            rowEstimatedTravelTimeEdit.Visible = false;
            rowNotesEdit.Visible = false;
        }

        protected void ddlVehicle_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<Storage.EntityModels.Users_VehicleDetails> vehicles = (List<Storage.EntityModels.Users_VehicleDetails>)Session["tripDetail_listVehicles"];
            if (vehicles == null)
            {
                Security.TripLoaUser us = Security.TripLoaUserManager.Instance.getUser(User.Identity.Name);
                vehicles = us.GetProfile().UsersVehiclesDetails;
            }
            VehiclesControl.Val = vehicles[ddlVehicle.SelectedIndex].VehicleDetails.VehicleClass;
            VehiclesControl.updateControl();
            Groupware.Trip trip = (Groupware.Trip)Session["tripDetail_TripGW"];
            
            setTripValuesControl(trip);
            updatePanelVehiclesControl.Update();
        }

        protected void ChangedFrequency(Object sender, EventArgs e)
        {
            setLabelFrequent(CheckBoxFrequent.Checked);
            UpdatePanelModeView.Update();
    
        }

        protected void setLabelFrequent(bool frequent)
        {
            if (frequent)
            {
                rowDepartureDateEdit.Visible = false;
                rowStartTimeEdit.Visible = false;
                rowArrivalDateEdit.Visible = false;
                rowEndTimeEdit.Visible = false;
                rowHourExpDate.Visible = false;
                rowResExpDate.Visible = false;
                rowFromDayFrequencyEdit.Visible = true;
                rowToDayFrequencyEdit.Visible = true;

                rowFromFrequent.Visible = true;
                rowToFrequent.Visible = true;
                rowDateNotFrequent.Visible = false;

                CheckBoxFrequent.Checked = true;
                btnShowOptionsFrequency.Visible = true;
            }
            else
            {
                rowDepartureDateEdit.Visible = true;
                rowStartTimeEdit.Visible = true;
                rowArrivalDateEdit.Visible = true;
                rowEndTimeEdit.Visible = true;
                rowResExpDate.Visible = true;
                rowHourExpDate.Visible = true;
                rowFromDayFrequencyEdit.Visible = false;
                rowToDayFrequencyEdit.Visible = false;

                rowFromFrequent.Visible = false;
                rowToFrequent.Visible = false;
                rowDateNotFrequent.Visible = true;

                CheckBoxFrequent.Checked = false;
                btnShowOptionsFrequency.Visible = false;
            }
        }

        /*private string[] getFrequencyDay(Groupware.Trip trip)
        {

            string[] times = new string[7];
            DateTime[] freq_time = trip.GetFrequencyDetails();

            for (int i = 0; i < 7; i++)
                if (freq_time[i] != null)
                {


                    times[i] = freq_time[i].ToString("hh:mm:ss");

                }
                else times[i] = "DayNotScheduled";
            return times;
        }*/


        protected void activateControl(Object sender, EventArgs e)
        {
            ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "interaction", "Sys.Application.add_load(bindMapEvents);", true);               
        }

        protected void changeViewEvent(Object sender, EventArgs e)
        {
            //read-only mode
            if (detailMultiView.ActiveViewIndex == 0)
            {
                ptc.Editable = false;
                
                UpdatePanelPeriodicTrip.Update();
            }
            else //edit mode
            {
                ptc.Editable = true;
                UpdatePanelPeriodicTrip.Update();
            }
        }
    }
}
